package com.pagoda.nerp.trade.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pagoda.nerp.trade.app.message.dto.MdMessageDto;
import com.pagoda.nerp.trade.common.PageListResult;
import com.pagoda.nerp.trade.dao.MdMessageDao;
import com.pagoda.nerp.trade.entity.MdMessage;
import com.pagoda.nerp.trade.service.MdMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MdMessageServiceImpl implements MdMessageService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MdMessageDao msgDao;

    /**
     * 查询消息个数
     *
     * @param params 供应商Id
     * @return 消息个数
     */
    @Override
    public Map<String,Object> queryMsgCount(Map<String,Object> params) throws Exception{
        // 1.参数处理
        int vendorId = 0;
        try {
            vendorId = Integer.parseInt(params.get("vendorId").toString());
        } catch (NumberFormatException e){
            throw new Exception("数字格式异常！");
        }

        // 2.如果返回0，判断是否为不存在的vendorId?
        int count = msgDao.countByVendorId(vendorId);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("count", count);
        return resultMap;
    }

    /**
     * 查询消息列表
     *
     * @param params 供应商Id
     * @return 消息列表
     */
    @Override
    public PageListResult<MdMessageDto> queryMsgList(Map<String,Object> params) throws Exception{
        // 1.参数处理
        int vendorId, pageNo, pageSize = 0;
        try {
            vendorId = Integer.parseInt(params.get("vendorId").toString());
            pageNo = null == params.get("pageNo") ? 0 : Integer.parseInt(params.get("pageNo").toString());
            pageSize = null == params.get("pageSize") ? 10 : Integer.parseInt(params.get("pageSize").toString());
        } catch (NumberFormatException e){
            throw new Exception("数字格式异常！");
        }

        // 2.分页处理
        Page pageInfo = PageHelper.startPage(pageNo, pageSize,true);

        // 3.查询
        List<MdMessage> mdMsgList = msgDao.selectByVendorId(vendorId);

        // 4.判断结果集是否为空
        if (null == mdMsgList){
            return null;
        }

        // 5.MdMessage转MessageDto
        List<MdMessageDto> msgList = new ArrayList<MdMessageDto>();
        MdMessageDto m = null;

        for(MdMessage msg :mdMsgList){
            m = new MdMessageDto();

            m.setId(msg.getId());
            m.setTitle(msg.getTitle());
            m.setMsgContent(msg.getMsgContent());
            m.setMsgCreateTime(msg.getMsgCreateTime());

            msgList.add(m);
        }

        return new PageListResult<MdMessageDto>(pageInfo, msgList);
    }
}
